package client;

import java.io.*;
import java.net.*;

public class Client extends Thread {

    private String host;
    private int port;
    static int status = 2;
    static int ON = 1;
    static int OFF = 2;
    Socket socket; //socket usado para enviar y recibir mensajes
    //Entrada y salida
    static DataInputStream bufferedReader;
    static DataOutputStream bufferedWriter;
    private int ncliente; //AGREGADO

    public Client() {
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getHost() {
        return this.host;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public int getPort() {
        return this.port  + (ncliente * 1000); //AGREGADO
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public int getStatus() {
        return status;
    }

    public void open_connection() {
        try {
            socket = new Socket(host, port + 1);
            bufferedReader = new DataInputStream(socket.getInputStream());
            bufferedWriter = new DataOutputStream(socket.getOutputStream());
            ncliente = bufferedReader.readInt(); //AGREGADO
            status = ON;
        } catch (Exception e) {
            status = OFF;
            System.out.println("Error al establecer conexion con el servidor." + e);           
        }
    }

    public void send_request(String request) {
        try {
            bufferedWriter.writeUTF(request);
        } catch (Exception ex) {
            System.out.println("Error irrecuperable durante la comunicacion con el servidor: " + ex);
        }
    }

    public String get_response() {
        String response = "";
        try {
            response = bufferedReader.readUTF();
        } catch (Exception ex) {
            System.out.println("Error irrecuperable durante la comunicacion con el servidor: " + ex);
        }
        return response;
    }

    public void close_connection() {
        try {
            socket.close();
            bufferedReader.close();
            bufferedWriter .close();
            status = OFF;
        } catch (Exception e) {
            System.out.println("No fue posible cerrar conexiones." + e);    
        }
    }

    public long get_timer() {
        long time = 0;
        try {
            time = bufferedReader.readLong();
        } catch (Exception ex) {
            System.out.println("Error irrecuperable durante la comunicacion con el servidor: " + ex);
        }
        return time;
    }
}
